import axios from 'axios'
import { version, baseURL, encryptSalt } from '@/config.js'
import store from '@/store/index'
import { joinRequestData, toast } from './index'
import md5 from 'md5'

const config = {
  baseURL: baseURL, // url = base url + request url
  timeout: 5000, // request timeout
  jumpLogin: true,
  headers: {
    platform: 'wechat',
    channel: 'mina',
    version,
    merchant: 'mG1in1i2QXiQ433Fd9UN55aVl6j5iW6AZ'
  }
}
// create an axios instance
const service = axios.create(config)
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['timestamp'] = Date.now()
    const requestData = {
      ...config.data,
      ...config.params,
      version: config.headers['version'],
      timestamp: config.headers['timestamp']
    }
    const waitString = joinRequestData(requestData)
    config.headers['sign'] = md5(md5(waitString) + encryptSalt)

    let appletId = uni.getStorageSync('AppletId')
    if (!appletId) {
      appletId = Date.now().toString() + (Math.floor(Math.random() * (9999999 - 1000000)) + 1000000).toString()
      uni.setStorage({ key: 'AppletId', data: appletId })
    }

    config.headers['Applet-Id'] = appletId
    config.headers['token'] = uni.getStorageSync('token') || ''
    config.headers['openid'] = uni.getStorageSync('openId') || ''
    config.headers['unionid'] = uni.getStorageSync('unionId') || ''
    config.headers['lat'] = uni.getStorageSync('nowLatitude') || ''
    config.headers['lon'] = uni.getStorageSync('nowLongitude') || ''
    config.headers['sid'] = uni.getStorageSync('sid') || ''
    config.headers['r-i'] = store.state.referer.i || ''
    config.headers['r-m'] = store.state.referer.m || ''
    config.headers['r-s'] = store.state.referer.s || ''
    config.headers['r-r'] = store.state.referer.r || ''
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

  /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
  response => {
    uni.hideLoading()
    const res = response.data
    if ((res.code === 101 || res.code === 102) && response.config.jumpLogin) {
      if (store.state.user.isLogin === true) {
        toast('您的登录信息已过期，请重新登录')
        uni.removeStorage('token')
      }
      uni.navigateTo({
        url: '/pages/register/register'
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else if (res.code === 150) {
      return res
    } else if (res.code !== 0) {
      if ((!response.config.noneAlert || response.config.noneAlert === false)) {
        toast(res.msg)
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    uni.hideLoading()
    toast(error.message)
    return Promise.reject(error)
  }
)

// axios 适配器
axios.defaults.adapter = function(config) {
  return new Promise((resolve, reject) => {
    var settle = require('axios/lib/core/settle')
    var buildURL = require('axios/lib/helpers/buildURL')
    uni.request({
      method: config.method.toUpperCase(),
      url: config.baseURL + buildURL(config.url,
        config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        console.log('执行完成：', response)
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        }
        settle(resolve, reject, response)
      }
    })
  })
}

export default service

export const upload = (params) => {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: baseURL + params.url,
      filePath: params.filePath,
      name: 'file_img',
      timeout: 10000,
      header: {
        ...config.headers,
        token: uni.getStorageSync('token') || '',
        openid: store.state.user.openid || '',
        unionid: store.state.user.unionid || ''
      },
      success(res) {
        uni.hideLoading()
        if (res.statusCode !== 200) {
          toast('上传失败')
          return reject(new Error('statusCode:' + res.statusCode))
        }
        const data = JSON.parse(decodeURIComponent(res.data))
        if (data.code === 101) {
          const token = uni.getStorageSync('token')
          if (token) {
            toast('您的登录信息已过期，请重新登录')
            uni.removeStorage('token')
          }
          uni.navigateTo({
            url: '/pages/register/register'
          })
          return reject(new Error(data.message || 'Error'))
        } else if (data.code !== 0) {
          toast(data.message)
          return reject(new Error(data.message || 'Error'))
        }
        resolve(data)
      },
      fail(err) {
        reject(new Error(err.errMsg))
      }
    })
  })
}
